/**
 * Created by yuji on 2015/10/28.
 */
var md5 = require('md5'),
    fs = require('fs'),
    path = require('path'),
    mkdirp = require('mkdirp');

'use strict'

/**
 * 生成md5后缀
 * 取七位
 * @param str
 * @returns {*}
 */
exports.md5Suffix  = function(buffer){
    return md5(buffer).slice(-7);
}


/**
 * 获取目录下的所有文件
 *输出形式是一个数组，每个元素是一个path字符串
 * @param path
 * @param arr
 * @returns {*}
 */
var traverseDir = exports.traverseDir = function(paths,arr) {
    arr = arr || [];
    paths = paths || '.';

    const fileList = fs.readdirSync(paths);
    const length = fileList.length;
    for (var i = 0; i < length; i++) {
        var fullPath = paths + '/' + fileList[i];
        var stat = fs.lstatSync(fullPath);
        if (stat.isDirectory()) {
            traverseDir(fullPath, arr);
        }
        else {
            var realPath = fullPath.replace(/^(\.\/)?/,'');
            arr.push(realPath);
        }
    }
    return arr;
}

/**
 * 生成新文件
 * @param base
 * @returns {Function}
 */
exports.newFile =  function(paths, hash, str){
        var ext = path.extname(paths),
            basename = paths.slice(0,-ext.length);
        var fullName = "../dist/"+basename +( hash? "_ "+ hash : "") + ext;
        var dirname = path.dirname(fullName);
    try{
        mkdirp.sync(dirname);
    }
     catch(e){
         console.log(e);
     }
       fs.writeFileSync( fullName,str);
        return "/" + basename +( hash? "_ "+ hash : "") + ext;
}


/**
 * 将set转换为数组
 * @param s
 * @returns {Array}
 */
exports.set2array = function(s){
    'use strict'
    let arr = [];
    for(let item of s ){
        arr.push(item);
    }
    return arr;

    //return Array.from(s);
    //坑爹的node v0.12不支持这个语法
}


exports.hasProp = function(ctx, key){
    return {}.hasOwnProperty.call(ctx, key);
}

//@TODO 需要一个根目录的路径
//获取完整路径
exports.parsePath = function(currentPath,filepath){
    var rootPath = ".";
    var absPath =  path.resolve(currentPath,'./'+filepath);
    return path.relative(rootPath,absPath);
}
//console.log(path.extname("a.js"))